
import { types, Instance, getParent, cast, destroy, SnapshotIn } from "mobx-state-tree"
import { MsgBase } from "./MsgBase";
import { HeaderModel } from "./Header";
import shortid from "shortid";

export type MsgItemModel = Instance<typeof MsgItem>
export type MsgItemsModel = Instance<typeof MsgItems>

const MsgItem = types
  .compose(
    MsgBase,
    types.model({
      id: types.identifier
    })
  )
  .actions(self => ({
    remove() {
      const parent = getParent<MsgItemsModel>(self, 2)
      parent.removeItem(cast(self))
    }
  }))

export const MsgItems = types
  .model({
    loading: types.optional(types.boolean, false),
    items: types.optional(types.array(MsgItem), [])
  })
  .actions(self => ({
    publishDraft: (msgDraft: SnapshotIn<HeaderModel>) => {
      const msgToPublish = { ...msgDraft, id: shortid() }
      self.items.unshift(msgToPublish);
    },
    removeItem: (item: MsgItemModel) => {
      destroy(item)
    },
  }));